import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Receiver {

	public static void main(String[] args) throws BroadcastException {
		AtomicBroadcast atomic = new AtomicBroadcast();
		Receiver reciever = new Receiver();
		ServerSocket serverSocket = reciever.criarServer();
		Processor processor = new Processor(args[0]);
		for (int i = 1; i < args.length; i++) {
			System.out.println("Adding Neighbor: " + args[i]);
			processor.addLink(args[i]);
		}

		InputStream inFromClient;
		Socket connectionSocket;

		while (true) {
			try {
				connectionSocket = serverSocket.accept();
				inFromClient = connectionSocket.getInputStream();
				ObjectInputStream objectInputStream = new ObjectInputStream(inFromClient);
				ProcessInfo clientMensage;
				try {
					clientMensage = (ProcessInfo) objectInputStream.readObject();
					System.out.println("Received Message: " + clientMensage.getBroadcast().getMessage() + " <> From: " + clientMensage.getSenderProcessor().getID());
					atomic.relay(processor,clientMensage);
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private ServerSocket criarServer() {
		ServerSocket welcomeSocket;
		try {
			welcomeSocket = new ServerSocket(1254);
			return welcomeSocket;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
